package com.ruix.app.ui.usercenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.SystemConfigMapper;
import com.ruix.app.model.AppUpgradeConfig;
import com.ruix.app.model.AppUpgradeInfo;
import com.ruix.app.model.SystemConfig;
import com.ruix.app.model.User;
import com.ruix.app.model.WebParcel;
import com.ruix.app.network.ApiConstant;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.network.RequestManager;
import com.ruix.app.service.UpdateAppService;
import com.ruix.app.ui.CommonWebActivity;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.DataCleanManager;
import com.ruix.app.util.LogUitl;
import com.ruix.app.widget.dialog.CommonDialog;
import com.ruix.app.widget.dialog.fragment.ListDialogFragment;
import com.ruix.app.widget.dialog.fragment.SimpleDialogFragment;
import com.ruix.app.widget.dialog.iface.IListDialogListener;
import com.ruix.app.widget.dialog.iface.IPositiveButtonDialogListener;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/5/4.
 */

public class SettingActivity extends BaseActivity implements View.OnClickListener, IPositiveButtonDialogListener {

    private TextView cacheSizeView,lastVersionView;
    private  AppUpgradeInfo info;
    private  AppUpgradeConfig appUpgradeConfig;
    private boolean downloading;
    private boolean downloadFinish;
    private String path;
//    private String apka = "http://up.hiwifi.com/HiWiFiPanda-android-release-6.5.2-170504-154322.apk";


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_usercenter_setting;
    }

    @Override
    protected void initView() {
        setTitle("设置");
        cacheSizeView = (TextView) findViewById(R.id.tv_cache_size);
        lastVersionView = (TextView) findViewById(R.id.tv_app_lastversion);
        caculatCacheSize();
    }

    @Override
    protected void initLocalData() {
//        checkUpgrade();
        loadCacheInfo();
        laodSystemInfo();

    }

    @Override
    protected void initListener() {
        findViewById(R.id.btn_logout).setOnClickListener(this);
        findViewById(R.id.ll_upgrade_app).setOnClickListener(this);
        findViewById(R.id.rl_clear_cache).setOnClickListener(this);
        findViewById(R.id.ll_seting_protocol).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_logout:
                showLogoutDialog();
                break;
            case R.id.ll_upgrade_app:
                if (appUpgradeConfig != null) {
                    if (downloadFinish && !TextUtils.isEmpty(path)){
                        installApk(path);
                        return;
                    }
                    if (downloading){
                        showErrorTip("下载中，稍等片刻。");
                       return;
                    }
                    webUpgrade();
                }

                break;
            case R.id.rl_clear_cache:
                showClearCacheDialog();

                break;
            case R.id.ll_seting_protocol:
                WebParcel parcel = new WebParcel();
                parcel.setTitle("用户协议");
                parcel.setUrl(ApiConstant.App_Agreement);
                startActivity(CommonWebActivity.newIntent(this, parcel));

                break;
        }
    }


    private void upgtadeApp(){
                            if (appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)) {
                        if (appUpgradeConfig.getLatestVersionUrl() != null){
                            downloadApk(appUpgradeConfig.getLatestVersionUrl());
                        }
                    } else {
                        showSuccessTip("已是最新版本");
                    }
    }

    private void webUpgrade(){
        if (appUpgradeConfig != null
                && !TextUtils.isEmpty(appUpgradeConfig.getLatestVersionUrl())
                && appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)) {
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
//            Uri content_url = Uri.parse(appUpgradeConfig.getLatestVersionUrl());
//            intent.setData(content_url);
//            startActivity(intent);
            downloading = true;
            showSuccessTip("开始下载");
            downloadApk(appUpgradeConfig.getLatestVersionUrl());
        } else {
            showSuccessTip("已是最新版本");
        }
    }


    private void logout() {
        showLoading();
        deleteOauth();
        RequestFactory.logout(new RXObserver() {

            @Override
            public void onSubscribe(Disposable d) {
                UserManager.sharedInstance().logoutHuanXin();
            }

            @Override
            public void onNext(Object value) {
                sendLogout();
                RequestManager.removeCookie();
            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
                dismissLoading();
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }

    private void deleteOauth(){
        UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }


    private void sendLogout() {
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_LOGOUT);
        sendBroadcast(intent);
        finish();
    }


    private void caculatCacheSize() {
        try {
            String size = DataCleanManager.getTotalCacheSize(this);
            cacheSizeView.setText(size);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void claerCache() {
        DataCleanManager.clearAllCache(this);
        caculatCacheSize();
        showSuccessTip("清除成功");
    }

    private void showClearCacheDialog() {
//        SimpleDialogFragment.createBuilder(this)
//                .setTitle("清除缓存")
//                .setMessage("")
//                .setPositiveButtonText(R.string.confirm)
//                .setNegativeButtonText(R.string.cancel)
//                .setRequestCode(101)
//                .show();

        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                claerCache();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("确定要清除缓存吗？");
    }

    private void showLogoutDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                logout();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("确定要退出登录吗？");
    }


    @Override
    public void onPositiveButtonClicked(int requestCode) {
        if (requestCode == 101) {

        } else if (requestCode == 102){

        }
    }

    private void checkUpgrade(){
        RequestFactory.checkAppUpgrade(null, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (value != null) {
                    info = new AppUpgradeInfo().parse(value);
                    lastVersionView.setText(info.getVersionShort());
                }
            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void laodSystemInfo() {
        RequestFactory.systemInfo(new SystemConfigMapper(), new RXObserver<SystemConfig>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(SystemConfig value) {
                if (value != null) {
                    appUpgradeConfig = value.getAppUpgradeConfig();
                    if (appUpgradeConfig != null){
                        if (appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)){
                            lastVersionView.setText("有版本更新");
                        } else {
                            lastVersionView.setText(RuiApplication.appVersionName);
                        }
                        CacheFactory.cacheAppUpgradeConfig(appUpgradeConfig);////缓存 离线下载
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void loadCacheInfo(){
        CacheFactory.loadAppUpgradeConfigt(new RXObserver<AppUpgradeConfig>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AppUpgradeConfig value) {
                if (value != null){
                    if (appUpgradeConfig != null
                            && appUpgradeConfig.isNeedUpgrade(RuiApplication.appVersionCode)){
                        lastVersionView.setText("有版本更新");
                    } else {
                        lastVersionView.setText(RuiApplication.appVersionName);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void downloadApk(String url){
        UpdateAppService.Builder.create(url)
                .setOnlyOnWifiWork(false)
                .setShowNotify(true)
                .setAutoUpdate(true)
                .build(this);

        if (myReceiver == null){
            registerReceivers();
        }
    }

    public  void installApk(String path) {
        Uri uri = Uri.fromFile(new File(path));
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(installIntent);
    }

    private BroadcastReceiver myReceiver;

    private void registerReceivers(){
        if (myReceiver ==  null){
            myReceiver = new DownloadBroadcastReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_DOWNLOAD_APK_FINISH);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
//        EaseUI.getInstance().popActivity(this);
    }

    private void unregisterReceivers(){
        if (myReceiver != null){
            unregisterReceiver(myReceiver);
        }
    }

    class DownloadBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_DOWNLOAD_APK_FINISH.equals(intent.getAction())){
                downloadFinish = true;
                path =  intent.getStringExtra("path_apk");

            }
        }

    };

}
